const express = require('express');
const mysql = require('mysql2/promise');
const cors = require('cors');
const app = express();
const port = 3000;

// MySQL连接池配置
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'testdb',
  waitForConnections: true,
  connectionLimit: 10
});

// 启用跨域和JSON解析
app.use(cors());
app.use(express.json());

// 示例API：查询用户数据
app.get('/api/students', async (req, res) => {
  console.log('ohhhhh')
  try {
    const [rows] = await pool.query('SELECT * FROM students');
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// 处理学生数据插入
app.post('/api/students', async (req, res) => {
    console.log(' app.post -- req:', req)
    try {
        const connection = await pool.getConnection();
        const [result] = await connection.query(
            'INSERT INTO students (student_name, student_age, month) VALUES ? ON DUPLICATE KEY UPDATE student_name = VALUES(student_name), student_age = VALUES(student_age), month = VALUES(month)',
            [req.body.map(item => [item.student_name, item.student_age, item.month])]
        );
        connection.release();
        res.status(201).json({ success: true, inserted: result.affectedRows });
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Database operation failed' });
    }
});

// 启动服务
app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});